package org.huoran.sakamichi.main.service;

import org.huoran.sakamichi.main.dao.model.User;
import org.huoran.sakamichi.main.dao.example.UserExample;
import org.huoran.sakamichi.main.dao.mapper.UserMapper;
import org.huoran.sakamichi.main.util.ResultBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class UserService {
	@Resource
	private UserMapper userMapper;
	
	/**
	 * 返回：根据用户名获取用户信息
	 * @param userName
	 * @return
	 */
	public ResultBean getUserByUserName(String userName){
		try{
			UserExample example = new UserExample();
			example.createCriteria()
					.andNicknameEqualTo(userName);
			List<User> userList = this.userMapper.selectByExample(example);
			if(userList.size() > 0){
				return ResultBean.success("获取用户信息成功", userList.get(0));
			}
			return ResultBean.none("没有此用户");
		}catch(Exception e){
			e.printStackTrace();
			return ResultBean.failed("获取用户失败");
		}
	}
	
	/**
	 * 返回：根据用户Id获取用户详情
	 * @param userId
	 * @return
	 */
	public ResultBean getUserById(String userId){
		User user = this.userMapper.selectByPrimaryKey(userId);
		if(user != null){
			return ResultBean.success("获取用户信息成功", user);
		}
		return ResultBean.failed("获取用户失败");
	}

	public boolean userLogin(String userName,String password){
		ResultBean userResult = this.getUserByUserName(userName);
		if(userResult.getStatus().equals(ResultBean.STATUS_OK)){
			if(((User)userResult.getResult()).getPassword() != null && ((User)userResult.getResult()).getPassword().equals(password)){
				return true;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}

	public void insertTransaction() {
		//插入正常数据
		User user = new User();
		user.setUserId(UUID.randomUUID().toString());
		user.setNickname("testUser");
		this.userMapper.insert(user);
		//插入主键为空的异常数据引起回滚
		User newUser = new User();
		newUser.setUserId(null);
		newUser.setNickname("testNull");
		this.userMapper.insert(newUser);
	}
}